import request from '@/utils/request'

// 定义通用API响应类型
interface ApiResponse<T> {
  code: number
  msg: string
  data: T
  count?: number
}

// 笔记类型定义
export interface Note {
  id: number
  title: string
  name: string
  content: string
  create_time: string
  update_time: string
  admin_id: number
  admin_name?: string
  author?: string // 创建者名称
  status?: number
  created_by?: number
  created_by_name?: string
  is_shared?: boolean
  shared_users: Array<{ id: number; name: string }>
  shared_departments: Array<{ id: number; name: string }>
  attachments: Array<{
    id: number
    name: string
    size: number
    path: string
    ext: string
    upload_time: string
  }>
  attachment_count?: number
  file_ids?: string
}

// 获取笔记列表
export function getNoteList(
  params?: any
): Promise<ApiResponse<{ list: Note[]; total: number; page: number; limit: number }>> {
  return request({
    url: '/api/disk/list',
    method: 'get',
    params: params,
  })
}

// 获取笔记详情
export function getNoteDetail(id: number): Promise<ApiResponse<Note>> {
  return request({
    url: '/api/disk/detail',
    method: 'get',
    params: { id },
  })
}

// 新建笔记
export function createNote(data: {
  title: string
  content?: string
  file_ids?: string
}): Promise<ApiResponse<Note>> {
  return request({
    url: '/api/disk/create',
    method: 'post',
    data: {
      title: data.title,
      content: data.content || '',
      file_ids: data.file_ids || '',
    },
  })
}

// 更新笔记
export function updateNote(data: {
  id: number
  title: string
  content: string
  file_ids?: string
}): Promise<ApiResponse<Note>> {
  return request({
    url: '/api/disk/update',
    method: 'put',
    data: {
      id: data.id,
      title: data.title,
      content: data.content,
      file_ids: data.file_ids || '',
    },
  })
}

// 删除笔记
export function deleteNote(id: number): Promise<ApiResponse<void>> {
  return request({
    url: '/api/disk/delete',
    method: 'delete',
    params: { id },
  })
}

// 分享笔记
export function shareNote(data: {
  id: number
  user_ids?: string
  department_ids?: string
}): Promise<ApiResponse<void>> {
  return request({
    url: '/api/disk/share',
    method: 'post',
    data,
  })
}

// 取消分享笔记
export function unshareNote(id: string): Promise<ApiResponse<void>> {
  return request({
    url: '/api/disk/unshare',
    method: 'post',
    data: { id },
  })
}

// 上传附件
export function uploadAttachment(formData: FormData): Promise<ApiResponse<any>> {
  return request({
    url: '/api/disk/upload-attachment',
    method: 'post',
    data: formData,
    headers: { 'Content-Type': 'multipart/form-data' },
  })
}

// 移除附件
export function removeAttachment(data: {
  noteId: number
  attachmentId: number
}): Promise<ApiResponse<void>> {
  return request({
    url: '/api/disk/remove-attachment',
    method: 'delete',
    params: { id: data.attachmentId, noteId: data.noteId },
  })
}

// 下载附件
export function downloadAttachment(id: number): Promise<Blob> {
  return new Promise((resolve, reject) => {
    // 使用正确的API路径，request拦截器会自动添加token认证
    request({
      url: '/api/file/download',
      method: 'get',
      params: { id },
      responseType: 'blob', // 关键：设置响应类型为blob
    })
      .then(response => {
        // 处理响应数据，确保返回Blob对象
        if (response.data instanceof Blob) {
          // 即使是Blob类型，也可能包含JSON错误信息
          // 检查是否是JSON格式的错误消息（通常来自401等错误）
          const fileReader = new FileReader()
          fileReader.onload = e => {
            try {
              // 尝试将Blob内容解析为JSON
              const text = e.target?.result as string
              const jsonData = JSON.parse(text)
              // 如果能解析出code字段，说明是API错误响应
              if (jsonData && typeof jsonData.code === 'number') {
                reject(new Error(`下载失败: ${jsonData.msg || '未知错误'}`))
              } else {
                // 不是JSON错误响应，返回原始Blob
                resolve(response.data)
              }
            } catch (e) {
              // 无法解析为JSON，说明是真正的文件
              resolve(response.data)
            }
          }
          fileReader.onerror = () => {
            // 如果读取失败，假设是正常的二进制文件
            resolve(response.data)
          }
          // 开始读取Blob内容
          fileReader.readAsText(response.data)
        } else if (typeof response.data === 'string') {
          // 如果返回的是字符串，尝试转为Blob
          try {
            // 检查是否是JSON字符串，如果是则尝试解析
            const jsonData = JSON.parse(response.data)
            reject(new Error(`下载失败: ${jsonData.msg || '未知错误'}`))
          } catch (e) {
            // 不是JSON，将字符串转为Blob
            const blob = new Blob([response.data], { type: 'application/octet-stream' })
            resolve(blob)
          }
        } else {
          reject(new Error('下载失败: 返回的数据格式无效'))
        }
      })
      .catch(error => {
        // 处理请求错误
        let errorMsg = '下载附件失败'
        if (error.response) {
          if (error.response.data && error.response.data.msg) {
            errorMsg = error.response.data.msg
          } else {
            errorMsg = `服务器错误: ${error.response.status}`
          }
        } else if (error.message) {
          errorMsg = error.message
        }
        reject(new Error(errorMsg))
      })
  })
}

// 下载文件
export function downloadFile(id: number): Promise<Blob> {
  return new Promise((resolve, reject) => {
    request({
      url: '/api/file/download',
      method: 'get',
      params: { id },
      responseType: 'blob',
    })
      .then(response => {
        if (response.data instanceof Blob) {
          resolve(response.data)
        } else {
          reject(new Error('下载失败: 返回的数据格式无效'))
        }
      })
      .catch(error => {
        let errorMsg = '下载文件失败'
        if (error.response && error.response.data && error.response.data.msg) {
          errorMsg = error.response.data.msg
        }
        reject(new Error(errorMsg))
      })
  })
}

// 保存笔记（综合新建和更新的功能）
export function saveNote(data: {
  id?: number
  name: string
  content: string
  file_ids?: string
  status?: number
}): Promise<ApiResponse<Note>> {
  // 根据是否有id来判断是创建还是更新
  if (data.id && data.id > 0) {
    return updateNote({
      id: data.id,
      title: data.name,
      content: data.content,
      file_ids: data.file_ids,
    })
  } else {
    return createNote({
      title: data.name,
      content: data.content,
      file_ids: data.file_ids,
    })
  }
}

// 关联附件到笔记
export function attachFilesToNote(data: {
  note_id?: number // 兼容旧参数名
  article_id?: number // 新参数名
  file_ids: string
}): Promise<ApiResponse<void>> {
  // 创建请求参数，确保包含正确的ID参数
  const requestData: any = { file_ids: data.file_ids }

  // 优先使用article_id，如果没有则使用note_id
  if (data.article_id !== undefined) {
    requestData.note_id = data.article_id
  } else if (data.note_id !== undefined) {
    requestData.note_id = data.note_id
  }

  return request({
    url: '/api/disk/attach-files',
    method: 'post',
    data: requestData,
  })
}

// 获取分享用户列表
export function getShareableUsers(): Promise<ApiResponse<Array<{ id: number; name: string }>>> {
  return request({
    url: '/api/disk/shareable-users',
    method: 'get',
  })
}

// 获取分享部门列表
export function getShareableDepartments(): Promise<
  ApiResponse<Array<{ id: number; name: string }>>
> {
  return request({
    url: '/api/disk/shareable-departments',
    method: 'get',
  })
}

// 搜索笔记
export function searchNotes(
  params?: any
): Promise<ApiResponse<{ list: Note[]; total: number; page: number; limit: number }>> {
  return request({
    url: '/api/disk/search',
    method: 'get',
    params: params,
  })
}

// 还原笔记
export function restoreNote(id: number): Promise<ApiResponse<void>> {
  return request({
    url: '/api/disk/restore',
    method: 'post',
    data: { id },
  })
}

// 彻底删除笔记
export function forceDeleteNote(id: number): Promise<ApiResponse<void>> {
  return request({
    url: '/api/disk/force-delete',
    method: 'delete',
    params: { id },
  })
}
